import java.util.concurrent.CountDownLatch;
import java.util.function.IntConsumer;

/**
 * @author hewei
 * @version 1.0
 * @description: 1116. 打印零与奇偶数
 * @date 2022/11/1 16:27
 */

public class ZeroEvenOdd {

    public static void main(String[] args) {
        ZeroEvenOdd zeroEvenOdd = new ZeroEvenOdd(5);
        Thread thread1 = new Thread(() -> {
            try {
                zeroEvenOdd.zero(System.out::println);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread thread2 = new Thread(() -> {
            try {
                zeroEvenOdd.odd(System.out::println);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread thread3 = new Thread(() -> {
            try {
                zeroEvenOdd.even(System.out::println);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread1.start();
        thread2.start();
        thread3.start();
    }

    private int n;
    private CountDownLatch count1;
    private CountDownLatch count2;
    private CountDownLatch count;

    public ZeroEvenOdd(int n) {
        this.n = n;
        count1 = new CountDownLatch(1);
        count2 = new CountDownLatch(1);
        count = new CountDownLatch(0);
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            count.await();
            printNumber.accept(0);
            count = new CountDownLatch(1);
            if (i % 2 == 0) {
                count1.countDown();
            } else {
                count2.countDown();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for (int i = 2; i <= n; i += 2) {
            count2.await();
            count2 = new CountDownLatch(1);
            printNumber.accept(i);
            count.countDown();
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i += 2) {
            count1.await();
            count1 = new CountDownLatch(1);
            printNumber.accept(i);
            count.countDown();
        }
    }
}
